import modelExtend from 'dva-model-extend'
import api from 'api'
const { pathToRegexp } = require("path-to-regexp")
import { pageModel } from 'utils/model'

const { queryRoleList,removeRole,updateRole,createRole, queryResourceTree,queryRoleResourceIds } = api

export default modelExtend(pageModel, {
  namespace: 'role',

  state: {
    resourceIds: [],
    currentItem: {},
    modalVisible: false,
    modalType: 'create',
  },

  subscriptions: {
    setup({ dispatch, history }) {
      history.listen(location => {
        if (pathToRegexp('/role').exec(location.pathname)) {
          dispatch({
            type: 'query',
            payload: {
              status: 2,
              ...location.query,
            },
          })
        }
      })
    },
  },

  effects: {
    *query({ payload }, { call, put }) {
      const data = yield call(queryRoleList, payload)
      if (data.success) {
        yield put({
          type: 'querySuccess',
          payload: {
            list: data.payload.list,
            pagination: {
              current: Number(payload.page) || 1,
              pageSize: Number(payload.pageSize) || 10,
              total: data.payload.total,
            },
          },
        })
      } else {
        throw data
      }
    },

    *delete({ payload }, { call, put, select }) {
      const data = yield call(removeRole, { id: payload })
      const { selectedRowKeys } = yield select(_ => _.user)
      if (data.success) {
        yield put({
          type: 'updateState',
          payload: {
            selectedRowKeys: selectedRowKeys.filter(_ => _ !== payload),
          },
        })
      } else {
        throw data
      }
    },
    *update({ payload }, { call, put }) {
      const data = yield call(updateRole, payload)
      if (data.success) {
        yield put({ type: 'hideModal' })
      } else {
        throw data
      }
    },
    *create({ payload }, { call, put }) {
      const data = yield call(createRole, payload)
      if (data.success) {
        yield put({ type: 'hideModal' })
      } else {
        throw data
      }
    },

    //请求资源树
    *queryResourceTree({payload}, {call, put}) {
      let data = yield call(queryResourceTree)
      if(payload.currentItem) {
        let rdata = yield call(queryRoleResourceIds,{id:payload.currentItem.id})
        payload.resourceIds = rdata.payload
      } else {
        payload.resourceIds = []
      }

      if(data.success) {
        payload.resourceTree = data.payload
        yield put({type: 'showModal', payload: payload})
      } else {
        throw data
      }
    }


  },

  reducers: {
    showModal(state, {payload}) {
      return {...state, ...payload, modalVisible: true}
    },

    hideModal(state) {
      return {...state, modalVisible: false}
    },
  }
})
